import math
from tkinter import filedialog
import os
class Calculator:
    def __init__(self):
        self.txt_list=[]
        self.data = []
    def get_mean(self):
        mean = sum(self.data) / len(self.data)
        return mean
    def get_vpp97(self):
        sorted_list = sorted(self.data)  # 由低到高
        low_index = math.floor(len(sorted_list) * 0.015)
        high_index = math.floor(len(sorted_list) * 0.985)
        vpp97 = sorted_list[high_index] - sorted_list[low_index]
        return vpp97
    def main(self):
        directory = filedialog.askdirectory()
        for filename in os.listdir(directory):
            if filename.endswith(".txt"):
                self.txt_list.append(os.path.join(directory,filename))
        for txtfile in self.txt_list:
            with open(txtfile, "r") as f:
                lines = f.readlines()
                for line in lines:
                    self.data.append(float(line.strip().strip(",")))
            m1 = self.get_mean()
            v1 = self.get_vpp97()
            with open("1.csv", "a") as f:
                f.write(f"{txtfile},{m1},{v1}\n")


my_calculator = Calculator()
my_calculator.main()